package com.cloudbroker.bcs.platform.dav.common.util;

import com.cloudbroker.bcs.common.util.EnvironmentUtils;
import com.cloudbroker.bcs.common.util.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.UUID;

public class FormatUtil {
    private static final Logger logger = LoggerFactory.getLogger(FormatUtil.class);

    public static byte[] wavToMp3(InputStream ips, String fileType,String classpath) {
        if( fileType.toLowerCase().equals("wav") ) {
            return wavToMp3(IOUtil.mark(ips) , classpath);
        }
        return IOUtil.streamToBytes(ips);
    }

    private static String getLamePath(String classpath) {
        classpath = IOUtil.ensureDir(classpath , "conf/" , "lame/");
        if( EnvironmentUtils.isOnWindows() ) {
            return classpath + "win/lame.exe -h ";
        } else {
            return classpath + "linux/lame -h ";
        }
    }

    private static byte[] wavToMp3(InputStream ips, final String classpath) {
        String tmpdir = IOUtil.ensureDir(classpath , "conf/" ,"tmp/");
        byte[] b = IOUtil.streamToBytes(IOUtil.reset(ips));
        File tmpWav = null , tmpMp3 = null;
        InputStream tmpIps = null;
        OutputStream ops = null;
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            final String tmpWavFileName = tmpdir + uuid;
            final String tmpMp3FileName = tmpdir + uuid + ".mp3";
            ops = new FileOutputStream(tmpWavFileName);
            tmpWav = new File(tmpWavFileName);
            IOUtil.copy(IOUtil.reset(ips) , ops , true);
            IOUtil.close(ops);
            Thread.sleep(200);
            EnvironmentUtils.exec(getLamePath(classpath) + " "+ tmpWavFileName + " " + tmpMp3FileName);
            tmpMp3 = new File(tmpMp3FileName);
            tmpIps = new BufferedInputStream(new FileInputStream(tmpMp3));
            return IOUtil.streamToBytes(tmpIps);
        }catch (Exception e) {
            logger.error("wav to mp3 error " , e);
        } finally {
            IOUtil.close(ips , ops , tmpIps);
            tmpWav.delete();
            tmpMp3.delete();
        }
        return b;
    }


}
